package net.asfun.jvalog.service;

import java.util.ArrayList;
import java.util.List;

import net.asfun.jvalog.common.JdoerFactory;
import net.asfun.jvalog.entity.Web;
import net.asfun.jvalog.frame.CachableView;
import net.asfun.jvalog.frame.JsonableView;
import net.asfun.jvalog.resource.MeterDao;
import net.asfun.jvalog.resource.WebDao;
import net.asfun.jvalog.util.UpdateManager;
import net.asfun.jvalog.vo.Blog;
import net.asfun.jvalog.vo.Link;
import net.asfun.jvalog.vo.Pager;
import net.asfun.jvalog.vo.Setting;
import net.asfun.jvalog.vo.Site;
import static net.asfun.jvalog.common.log.logger;


public class SiteService {
	
	public static void reset() {
		//setting
		Setting.reset();
		//site
		Site.reset();
		//view
		CachableView.reset();
		JsonableView.reset();
		logger.info("*********************reset static object");
	}
	
	public static void reCount() {
		MeterDao.reBuild();
		logger.info("*********************rebuild number counter");
	}

	public static List<Link> getFriendLink() {
		List<Link> links = new ArrayList<Link>();
		for ( Web web : WebDao.listPublished() ) {
			links.add(new Link(web));
		}
		return links;
	}

	public static void update(Blog site) {
		UpdateManager.enableStaticTask();
	}

	public static List<Link> listAllLink(Pager pager) {
		List<Link> links = new ArrayList<Link>();
		for(Web web : WebDao.listAll(pager)) {
			links.add(new Link(web));
		}
		return links;
	}

	public static void addLink(Web web) {
		JdoerFactory.jdoWeb.save(web);
		if ( web.getFlag() == Web.FLAG_VISFRI ) {
			UpdateManager.enableCacheTask();
		}
	}

	public static void delete(Long id) {
		Web web = JdoerFactory.jdoWeb.load(id);
		if ( web.getFlag() == Web.FLAG_VISFRI ) {
			UpdateManager.enableCacheTask();
		}
		JdoerFactory.jdoWeb.delete(web);
	}

	public static Link getById(Long id) {
		return new Link(JdoerFactory.jdoWeb.load(id));
	}

	public static void updateLink(Web web) {
		Web record = JdoerFactory.jdoWeb.load(web.getKey().getId());
		if ( record.getFlag() == Web.FLAG_VISFRI || 
				web.getFlag() == Web.FLAG_VISFRI) {
			UpdateManager.enableCacheTask();
		}
		record.setDescription(web.getDescription());
		record.setFlag(web.getFlag());
		record.setImage(web.getImage());
		record.setTitle(web.getTitle());
		record.setUrl(web.getUrl());
	}
}
